<template>
    <div class="other-top-head head-fixed" style="box-shadow: rgba(0, 0, 0, 0) 0px 0px 0px 0px">
        <div class="navbar-wrap">
            <div class="new-nav-page scroll-white" style="width: 100%">
                <headerCon></headerCon>
            </div>
        </div>
    </div>
    <div class="recharge-base"
        :style="{ background: `url(${siteConf.recharge.recharge_bg})`, backgroundRepeat: 'no-repeat', backgroundPosition: 'top' }">
        <div class="recharge-header">
            <div class="w1406">
                <div class="header-gif"
                    :style="{ background: `url(${siteConf.recharge.recharge_header_img})`, backgroundRepeat: 'no-repeat', backgroundPosition: 'center' }">
                </div>
                <div class="header-text">
                    <h4>享重复下载模型永久免费最新特权</h4>
                    <!-- <p>活动时间：11月01日-12月26日</p> -->
                </div>
            </div>
        </div>
        <div class="recharge-conventional new-recharge-conventional">
            <div class="w1406">
                <div class="recharge-base-h">
                    <div class="h-bg"
                        :style="{ background: `url(${siteConf.recharge.recharge_title_bg})`, backgroundRepeat: 'no-repeat' }">
                        <h3>{{ siteConf.recharge.recharge_title || '下载币充值' }}</h3>
                    </div>
                    <!-- <h4>用于素材下载：下载币包括赠点+溜点，即充即用，永久有效</h4> -->
                </div>
                <div class="conventional-list">
                    <ul class="clearfix">
                        <li v-for="(item, index) in userConfig.coinType" :key="index"
                            :style="{ background: `url(${siteConf.recharge.recharge_coin_bg})`, backgroundRepeat: 'no-repeat' }">
                            <div class="conventional-t-p1"><b>{{ item.coin }}</b><span>下载币</span></div>
                            <div class="conventional-sbox clearfix">
                                <div class="conventional-t-p3">￥<span>{{ item.price - item.discount_price }}</span>
                                </div>
                                <div class="conventional-t-p2" v-if="item.is_discount == 1"><span>￥{{ item.price
                                        }}</span>
                                </div>
                            </div>
                            <div :class="item.is_discount == 1 ? 'conventional-t-p4' : 'conventional-t-p5'"><span
                                    v-if="item.is_discount == 1">优惠{{ item.discount_price }}</span></div>
                            <div class="conventional-line"><i></i><span>充值获得</span><i></i></div>
                            <div class="conventional-gift">
                                <span class="recharge-mode-btn"><b></b> 可获赠{{ item.give_score || 0 }}积分</span>
                            </div>
                            <div class="recharge-btn-base conventional-btn">
                                <button type="button" class="rechargeBtn"
                                    :style="{ background: `url(${siteConf.recharge.recharge_btn_img})`, backgroundRepeat: 'no-repeat', backgroundPositionX: '-10px', backgroundPositionY: '-76px' }"
                                    @click.stop="rechargeClick(item)">立即充值</button>
                                <!-- <button >立即充值</button> -->
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>

        <div class="recharge-problem new-recharge-problem">
            <div class="w1406">
                <div class="recharge-base-h">
                    <div class="h-bg" :style="{ backgroundImage: `url(${siteConf.recharge.recharge_title_bg})` }">
                        <h3>{{ siteConf.recharge.question_title || '常见问题' }}</h3>
                    </div>
                </div>
                <div class="problem-box"
                    :style="{ background: `url(${siteConf.recharge.ask_bg})`, backgroundRepeat: 'no-repeat', backgroundPosition: 'center' }">
                    <div class="problem-box-item" v-for="(item, index) in askedQuestionData" :key="index">
                        <p>{{ item.title }}</p>
                        <p v-html="item.text"></p>
                    </div>
                    <div class="problem-box-item">
                        <p>其他充值疑问请随时联系我们<span>客服</span><a class="item-qq" :href="siteConf.recharge.qq_href"
                                target="_blank">{{ siteConf.recharge.qq_config || 'qq' }}</a></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- 充值弹窗 -->
    <el-dialog class="notice-dialog" v-model="coinDialogVisible" :close-on-press-escape="false" width="800" height="480"
        append-to-body align-center modal-class="overlay-modal" @close="closeDialog" :z-index="100000000"
        :close-on-click-modal="false" style="border-radius: 16px !important; padding: 0 !important">
        <div class="global-pay clearfix">
            <div class="left pay-type-class11"
                :style="{ background: `url(${siteConf.recharge.pay_bg})`, backgroundRepeat: 'no-repeat', backgroundPosition: 'center' }">
                <h2>{{ coinCount }}下载币</h2>
                <div class="package-gift">
                    <h4>赠送明细</h4>
                    <p>可获赠{{ giveSocre }}积分</p>
                </div>
            </div>
            <div class="right vipprice-styles">

                <div class="form-cell clearfix">
                    <label>充值账号：</label>
                    <div class="user-info clearfix">
                        <img :src="userInfo.avatar" alt="">
                        <p><span>{{ userInfo.username }}</span><i>（{{ userInfo.label_id }}）</i></p>
                    </div>
                </div>
                <!-- vipprice-top -->
                <div class="form-cell tab-payment clearfix vipprice-top" style="margin-top: 13px;">
                    <label>付款方式：</label>
                    <div class="payway payway-new ab2" style="display:flex;align-items: center;">
                        <el-space wrap>
                            <div v-for="(type, typeindex) in userConfig.payType" :key="typeindex">
                                <div class="paytype " v-if="type.name !== 'blance'"
                                    :class="isActivePay == type.id ? 'paytypeactive' : ''" @click="payClick(type)">
                                    {{ type.title }}</div>
                            </div>

                        </el-space>
                    </div>
                </div>
                <!-- 支付宝微信扫码支付价格 -->
                <div class="amount price">
                    <span>{{ payPrice }}</span>元<em></em>
                </div>

                <!-- <div class="pop-recharge-vipprice">
     
                    <div class="vipprice1 discount-y1" style="display: block;">
                        VIP实付金额：<span>189元</span>
                        <b class="goto-open" data-vip_type="1" data-entrance="2">8折购VIP</b>
                    </div>
                </div> -->

                <div class="pay-content">
                    <!-- 微信扫码支付 -->
                    <div class="pay-output show pay-wechatpay">
                        <div class="qrcode">
                            <img :src="payArr" @error.once="useDefaultImage" />
                        </div>
                        <p class="pay-type-text">微信/支付宝扫码支付</p>
                        <div class="expire-pay" :style="isRefresh ? 'display: block;' : 'display: none;'"
                            v-if="isRefresh" @click="refreshPay"><i></i><span>二维码已超时<br>请刷新</span></div>
                    </div>
                    <!-- 加载层 -->
                    <div class="pay-loadding" :style="isLoading ? 'display: block;' : 'display: none;'">
                        <span></span>
                        <em>正在加载...</em>
                    </div>


                </div>


            </div>
        </div>

    </el-dialog>

    <login></login>
    <footerContent></footerContent>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import headerCon from "../../components/header.vue";
import login from "../../components/login.vue";
import { useUserConfig } from "../../stores/userConfig";
const userConfig = useUserConfig(); //配置信息
import { useUserInfo } from "../../stores/userInfo";
const userInfo = useUserInfo(); //获取用户信息
import footerContent from "../../components/footerContent.vue";
import eventBus from '../../utils/event-bus';
import { checkPay, createOrder, alipay,doPayment } from "../../api/pay";
import { askedQuestion } from "../../api/product";
import { useSiteConfig } from '../../stores/siteConfig'
import router from '../../router'
const siteConf = useSiteConfig()
const coinDialogVisible = ref(false) //支付弹窗
const isLoading = ref(true); //加载

const payPrice = ref(0) //支付金额
const coinCount = ref(0);
const giveSocre = ref(0)
const recharge_coin_id = ref(0)
//默认图片
const useDefaultImage = (event: any) => {
    event.target.src = siteConf.defalut_product_img
}
//判断字符串是否为空
const isEmpty = (str: string) => {
    return !str;
}
//立即充值  打开弹窗
const rechargeClick = (item: any) => {
    if (!userInfo.isLogin()) {
        eventBus.emit('customEvent', {
            dis: true
        })
    } else {
        if (isEmpty(userInfo.mobile)) {
            ElMessage.error("请绑定手机号");
            setTimeout(() => {
                router.push({ path: '/account_sys' })
            }, 2000)
            return
        } else {
            recharge_coin_id.value = item.id || 0
            giveSocre.value = item.give_score || 0
            coinCount.value = item.coin || 0
            payPrice.value = item.is_discount == 1 ? (item.price - item.discount_price) : item.price
            coinDialogVisible.value = true
            createOrderData.pay_price = item.is_discount == 1 ? (item.price - item.discount_price) : item.price
            createOrderData.recharge_coin_id = item.id || 0
            isLoading.value = false
            createOrderInfo(createOrderData)
        }
    }
}
//支付方式
const isActivePay = ref(1);
const payClick = (item: any) => {
    isActivePay.value = item.id;
    createOrderData.pay_type = item.id;
    createOrderInfo(createOrderData)
};
//关闭弹窗
const closeDialog = () => {
    isActivePay.value = 1; //重置支付方式
    giveSocre.value = 0
    coinCount.value = 0
    payPrice.value = 0
    coinDialogVisible.value = false
    stopPolling()
}

interface orderItemForm {
    pay_price: number;
    vip_price_id: number;
    recharge_coin_id: number;
    pay_type: number;
    recharge_type: number;
    vip_type: number;
    remark: string;
}
//订单信息初始化
const createOrderData = reactive<orderItemForm>({
    pay_price: payPrice.value,//支付价格
    vip_price_id: 0, //vip表价格
    recharge_coin_id: recharge_coin_id.value, //金币表id
    pay_type: isActivePay.value, //支付类型
    recharge_type: 2, //金币
    vip_type: 0,
    remark: '金币充值',

});

//创建订单
const order_no = ref("");
const createOrderInfo = (createOrderData: any) => {
    createOrder({ createOrderData: createOrderData })
        .then((res: any) => {
            if (res.code == 1) {
                order_no.value = res.data.order_no;
                paymentFun();
            }
        })
        .catch((error: any) => {
            ElMessage.error(error.msg)
    });
};

const payArr = ref<any>([]);
//支付
const paymentFun = () => {
    isLoading.value = true;
    doPayment({ order_sn: order_no.value,tab:isActivePay.value })
        .then((res: any) => {
            if (res.code == 1) {
                payArr.value = res.data;
                isLoading.value = false;
                startPolling(); //轮询
            }
        })
        .catch((error) => {
            ElMessage.error("其他错误"+error);
        });
};
//检查订单是否支付
const check_pay = async () => {
    try {
        // 获取下载的url  
        const res: any = await checkPay({ order_no: order_no.value });
        if (res.code === 1) {
            await userInfo.fetchUserInfo();
            coinDialogVisible.value = false;
            //停止轮询
            stopPolling();
        }
    } catch (error: any) {
        if (error.code == 203) {
            //isRefresh.value = true;
            //停止轮询
            stopPolling();
        }
    }
}
//刷新二维码
const isRefresh = ref(false);
const refreshPay = () => {
    isRefresh.value = false;
};

//轮询
const intervalId = ref<number | null>(null);
const startPolling = () => {
    if (intervalId.value !== null) return;
    intervalId.value = window.setInterval(check_pay, 2000); // 每1秒轮询一次
};

//停止轮询
const stopPolling = () => {
    if (intervalId.value !== null) {
        window.clearInterval(intervalId.value);
        intervalId.value = null;
    }
};

//获取常见问题
const askedQuestionData = ref<any>([]);
askedQuestion({ q_type: 0 }).then((res: any) => {
    if (res.code == 1) {
        askedQuestionData.value = res.data
    }
}).catch((err) => {
    console.log(err)
})

</script>
<style>
@import url("@/style/recharge.css");
</style>